package jgcp.master.network;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Observable;

import jgcp.common.network.Connection;
/**
 * 
 * @Date 31/05/2009
 * @author Jie Zhao (288654)
 * @version 1.0
 */
public class WorkerList extends Observable{
	private static WorkerList instance = new WorkerList();
	public static WorkerList getInstance()
	{
		return instance;
	}
	
	private WorkerList(){}
	private List<Connection> nodes = Collections.synchronizedList(new ArrayList<Connection>());
	/**
	 * Return the number of workers.
	 * @return
	 */
	public synchronized int numberOfWorkers()
	{
		return nodes.size();
	}
	
	/**
	 * return the list of worker ids.
	 * @return
	 */
	public List<Integer> getWorkerList()
	{
		List<Integer> result = new ArrayList<Integer>();
		for(Connection c:nodes)
		{
			result.add(c.getId());
		}
		return result;
	}
	
	/**
	 * add a new worker to the list.
	 * @param c
	 */
	public synchronized void addWorker(Connection c)
	{
		if(c == null)return;
		nodes.add(c);
		setChanged();
		notifyObservers();
	}
	/**
	 * remove a worker from the list
	 * @param workerId
	 */
	public synchronized void removeWorker(int workerId)
	{
		Connection con = null;
		for(Connection c:nodes)
		{
			if(c.getId() == workerId)
			{
				con = c;
			}
		}
		if(con != null)nodes.remove(con);
		setChanged();
		notifyObservers();
	}
	public synchronized Connection getConnection(int workerId)
	{
		for(Connection c:nodes){
			if(c.getId() == workerId)return c;
		}
		return null;
	}
	
}
